package com.ys.web.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.UUID;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.ys.extend.ImportStateRecord;
import com.ys.extend.utils.ContextHolderUtils;
import com.ys.web.dao.CommonDao;
import com.ys.web.pojo.BackupInfo;
import com.ys.web.pojo.CompanyInfo;
import com.ys.web.service.AccountService;
import com.ys.web.service.BackupService;
import com.ys.web.service.CompanyService;
import com.ys.web.service.ImportBaiduCSVService;
import com.ys.web.ws.service.CompanyInfoRemoteService;
import com.ys.web.ws.service.ManageCompanyInfoService;

@Scope("prototype")
@Controller
public class UploadBebFileController extends HttpServlet{

	private String uploadPath;
	private String extensions;
	private static final ResourceBundle bundleOfBeb = ResourceBundle.getBundle("upload");

	@Autowired
	CompanyService companyService;

	@Autowired
	AccountService accountService;

	@Autowired
	ImportBaiduCSVService importBaiduCSVService;
	
	@Autowired
	BackupService backupService;
	
	@Autowired 
	ManageCompanyInfoService manageCompanyInfoService;
	
	

	@RequestMapping(value = "uploadBebFile.do", method = RequestMethod.POST)
	public String uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {

		response.setCharacterEncoding("UTF-8");

		String companyId = request.getParameter("companyId");// 获取公司id
		String accountId = request.getParameter("accountId");// 获取账户id

		Integer userId = null;

		Integer companyIdNum = null;
		Integer accountIdNum = null;
		
		String initFileName = null;//上传文件名
				try {
					companyIdNum = Integer.valueOf(companyId);
					accountIdNum = Integer.valueOf(accountId);
				} catch (Exception e) {
					response.getWriter().write("错误的参数类型");
					return "错误的参数类型";
				}
				
				
				Integer chunk = null; /* 分割块数 */
				Integer chunks = null; /* 总分割数 */
				String tempFileName = null; /* 临时文件名 */
				String newFileName = null; /* 最后合并后的新文件名 */
				String[] extensionsArray = null;/* 要过滤的扩展名数组 */
				BufferedOutputStream outputStream = null;
				uploadPath = bundleOfBeb.getString("uploadBebPath");
				extensions = bundleOfBeb.getString("bebextensions");

				File up = new File(uploadPath);

				if (!up.exists()) {
					up.mkdir();
				}
				// 判断文件是否文件

				if (ServletFileUpload.isMultipartContent(request)) {

					try {

						DiskFileItemFactory factory = new DiskFileItemFactory();
						factory.setSizeThreshold(1024);// 设置流的每次读取大小，相当于bufferStream
						ServletFileUpload upload = new ServletFileUpload(factory);
						upload.setHeaderEncoding("UTF-8");
						upload.setSizeMax(50 * 1024 * 1024);// 设置附件最大大小，超过这个大小上传会不成功
															// 50m*/
						List<FileItem> items = upload.parseRequest(request);// 分割文件请求
						// MultipartHttpServletRequest multHttpServletRequest =
						// (MultipartHttpServletRequest)request;
						
						System.out.println(items.size());
						// System.out.println("item:"+items.size());
						for (FileItem item : items) {
							if(item.getName()!=null){
								System.out.println(item.getName());
								
								initFileName =  item.getName();
								
								initFileName = initFileName.substring(0,initFileName.indexOf(".beb"));
								System.out.println(initFileName);
							}
							// System.out.println("go");
							if (item.isFormField()) {// 判断该表单项是否是普通类型
								if (item.getFieldName().equals("name")) {
									System.out.println("tempFileName1:" + tempFileName);
									tempFileName = item.getString();
									System.out.println("临时文件名：" + tempFileName);
								} else if (item.getFieldName().equals("chunk")) {
									System.out.println("tempFileName2:" + tempFileName);
									chunk = Integer.parseInt(item.getString());
									System.out.println("当前文件块：" + (chunk + 1));
								} else if (item.getFieldName().equals("chunks")) {
									System.out.println("tempFileName3:" + tempFileName);
									chunks = Integer.parseInt(item.getString());
									System.out.println("文件总分块：" + chunks);
								}
							} else {
								System.out.println("tempFileName4:" + tempFileName);
								if (tempFileName != null) {
									String chunkName = tempFileName;
									if (extensions != null) {
										extensionsArray = extensions.split(",");
										String es = FilenameUtils.getExtension(tempFileName);
										boolean extensionExists = false;
										for (String extension : extensionsArray) {
											if (extension.equals(FilenameUtils.getExtension(tempFileName))) {//将upload.properties文件的extension的后缀名数组逐个与当前文件后缀对比
												// Map<String, Object> m = new
												// HashMap<String, Object>();
												// m.put( "status", false );
												// m.put("message",
												// "请上传正确的文件类型");
												// response.getWriter().write(
												// JSON.toJSONString( m ) );
												// return;
												extensionExists = true;
											}

										}
										
										//当前文件后缀与upload.properties文件的extension的后缀不匹配
										if (extensionExists == false) {
											Map<String, Object> m = new HashMap<String, Object>();
											m.put("status", false);
											m.put("message", "导入失败,请上传正确的文件类型");
											response.getWriter().write(JSON.toJSONString(m));
											return "";
										}
									}
									if (chunkName != null) {
										chunkName = chunk + "_" + tempFileName;
									}

									File saveFile = new File(uploadPath, chunkName);
									
									item.write(saveFile);

								} // 写入文件块
							}

						}
						if (tempFileName == null) {
							Map<String, Object> m = new HashMap<String, Object>();
							m.put("status", false);
							m.put("message", "导入失败");
							response.getWriter().write(JSON.toJSONString(m));
							return "";

						}
						// System.out.println("tempFileName:"+tempFileName);
						newFileName = initFileName+"_"+UUID.randomUUID().toString().replace("-", "").concat(".")
								.concat(FilenameUtils.getExtension(tempFileName));

						if (chunk != null && chunk + 1 == chunks) {
							File uploadFile = new File(uploadPath, newFileName);
							outputStream = new BufferedOutputStream(new FileOutputStream(uploadFile));
							// 输建一个文件对象，根据文件对象输建一个文件输出流，把文件输出流转化为缓冲流
							/* 遍历文件块合并 */
							for (int i = 0; i < chunks; i++) {
								// 创建临时文件对象
								File tempFile = new File(uploadPath, i + "_" + tempFileName);
								// 临时文件转成字节流
								byte[] bytes = FileUtils.readFileToByteArray(tempFile);
								outputStream.write(bytes);// 把字节流按序写入
								outputStream.flush();// 刷新缓存
								tempFile.delete();// 删除临时文件
							}

							outputStream.flush();// 合并所有后刷新缓存
						}

						Map<String, Object> m = new HashMap<String, Object>();
						String filePath = bundleOfBeb.getString("uploadBebPath") +"/" + newFileName;
						m.put("status", true);
						m.put("fileUrl", filePath);
						m.put("message", "导入成功");
						response.getWriter().write(JSON.toJSONString(m));

						
						//csv文件导入数据库
						
							BackupInfo backupInfo = new BackupInfo();
//							private Integer id;
//							private String path;
//							private Integer companyId;
//							private String companyName;
//							private Date createTime;
//							private Integer is_good;
							CompanyInfo companyInfo =  manageCompanyInfoService.getEntity(Integer.valueOf(companyId));
							
							String companyName = companyInfo.getCompanyName();
							Date createTime = new Date();
							backupInfo.setPath(filePath);
							backupInfo.setCompanyId(Integer.valueOf(companyId));
							backupInfo.setCompanyName(companyInfo.getCompanyName());
							backupInfo.setCreateTime(createTime);
							backupInfo.setIsGood(0);
							backupInfo.setDescription(initFileName);
							backupService.saveBackupInfo(backupInfo);
							String username = (String) ContextHolderUtils.getSession().getAttribute("username");
							ImportStateRecord.addStateMsg(username, "导入成功");
						
						

					} catch (FileUploadException e) {
						e.printStackTrace();
						Map<String, Object> m = new HashMap<String, Object>();
						m.put("status", false);
						response.getWriter().write(JSON.toJSONString(m));
					} catch (Exception e) {
						e.printStackTrace();
						Map<String, Object> m = new HashMap<String, Object>();
						m.put("status", false);
						response.getWriter().write(JSON.toJSONString(m));
					} finally {
						try {
							if (outputStream != null)
								outputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}

			

		
		return "success";
	}
	
				
	
	
	
}
